import sys
import os
from PyQt5.QtWidgets import QApplication
from ui.main_window import MainWindow
from core.platform_auth import platform_auth
import asyncio
import nest_asyncio
from qasync import QEventLoop

# 添加环境变量控制
ENABLE_DAHUA_AUTH = os.getenv('ENABLE_DAHUA_AUTH', 'true').lower() == 'true'

def main():
    # 允许嵌套事件循环
    nest_asyncio.apply()
    
    app = QApplication(sys.argv)
    
    # 使用 qasync 的事件循环
    loop = QEventLoop(app)
    asyncio.set_event_loop(loop)
    
    window = MainWindow()
    window.show()
    
    # 初始化认证
    async def init():
        if ENABLE_DAHUA_AUTH:
            try:
                await platform_auth.initialize()
            except Exception as e:
                print(f"初始化大华认证失败: {e}")
    
    # 运行初始化
    loop.run_until_complete(init())
    
    # 修改清理逻辑
    async def cleanup():
        if ENABLE_DAHUA_AUTH:
            try:
                await platform_auth.shutdown()
            except Exception as e:
                print(f"清理过程发生错误: {e}")
    
    # 使用异步方式处理清理
    def sync_cleanup():
        if ENABLE_DAHUA_AUTH:
            try:
                # 创建新的事件循环来处理清理
                cleanup_loop = asyncio.new_event_loop()
                asyncio.set_event_loop(cleanup_loop)
                cleanup_loop.run_until_complete(cleanup())
                cleanup_loop.close()
            except Exception as e:
                print(f"同步清理过程发生错误: {e}")
    
    # 连接同步清理函数
    app.aboutToQuit.connect(sync_cleanup)
    
    # 使用 qasync 的事件循环运行
    try:
        with loop:
            loop.run_forever()
    except Exception as e:
        print(f"主事件循环发生错误: {e}")

if __name__ == "__main__":
    main() 